﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace FloatingWindowTools
{
    public class MapbasicWindowWrapper : Window
    {
        private static IntPtr HookHandle;
        private WinAPI.HookProc mapbasicHook;

        public MapbasicWindowWrapper(MapinfoWrapper mapInfo, int windowID)
            : base(mapInfo,windowID)
        { }

        public int MapbasicWindowHook(int nCode, IntPtr wParam, ref FloatingWindowTools.WinAPI.CWPSTRUCT cwp)
        {
            // Listen for rich text text update messages and tell any handlers about it.
            if (cwp.message == 0x00C2)
            {
                string pointerValue = Marshal.PtrToStringAnsi(cwp.lparam);
                if (this._textupdated != null)
                    this._textupdated(pointerValue);

            }
            // Call the next hook.
            return WinAPI.CallNextHookEx(HookHandle, nCode, wParam, ref cwp);
        }

        private Action<String> _textupdated;
        /// <summary>
        /// Event fired when the text is updated in the MapInfo mapbasic window.
        /// Adding a handler to this event causes the MapInfo mapbasic window to be hooked
        /// to listen for text changes.
        /// Removing the handler removes the hooks and show be called before the application closes.
        /// <para>Note: This event can only have one handler.</para>
        /// </summary>
        public event Action<String> TextUpdated
        {
            add
            {
                this.mapbasicHook = new FloatingWindowTools.WinAPI.HookProc(MapbasicWindowHook);
                HookHandle = WinAPI.SetWindowsHookEx(WinAPI.HookType.WH_CALLWNDPROC, mapbasicHook, WinAPI.GetModuleHandle(null), Convert.ToUInt32(this.OwnerThreadId.ToInt32()));
                this._textupdated += value;
            }
            remove
            {
                WinAPI.UnhookWindowsHookEx(HookHandle);
                this._textupdated -= value;
            }
        }
    }
}
